package com.yang.service;

import com.yang.dao.RoleDao;
import com.yang.pojo.Role;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RoleService {
    RoleDao roleDao = new RoleDao();
    //调用RoleDao查询所有角色
    public ArrayList<Role> findAllRole() throws SQLException {

        ArrayList<Role> roles = roleDao.selectAllRole();
        return roles;
    }

    //保存用户信息
    public boolean addRole(String roleName,String roleDesc,String[] menuIds) throws SQLException {
         boolean b = true;
        //返回的值就是管理员id
        int roleId = roleDao.insertRole(roleName, roleDesc);
        //接收页面传过来的参数
        for (int i = 0; i < menuIds.length; i++) {
            int menuId = Integer.parseInt(menuIds[i]);
            int j = roleDao.insertRoleAndMenus(roleId, menuId);
            b = b&&j>0;
        }

        return b;
    }

    //根据roleId删除用户id与menuId之间的关系和删除用户信息
    public boolean deleteRole(int roleId) throws SQLException {
        boolean b = true;
        int i = roleDao.deleteRoleAndMenus(roleId);
        int j = roleDao.deleteRole(roleId);
        if(i+j <= 0){
            b = false;
        }
        return b;
    }

    //根据roleId查询角色信息
    public Role findRoleById(int roleId) throws SQLException {
        Role roles = roleDao.selectRoleById(roleId);
        return roles;
    }

    //根据角色id查询角色拥有的权限菜单的id
    public List<Integer> findMenuIdByRoleId(int roleId) throws SQLException {
        List<Integer> menuIdList = roleDao.selectMenuIdByRoleId(roleId);
        return menuIdList;
    }

    //根据角色id修改角色信息和新增当前角色的菜单关联
    public boolean updateRole(String roleName,String roleDesc,int roleId,String[] menuIds) throws SQLException {

        //修改角色信息
        int i = roleDao.updateRole(roleName, roleDesc, roleId);
        //删除当前角色权限
        int j = roleDao.deleteRoleAndMenus(roleId);
        //新增选择的所有权限
        for (int k = 0; k < menuIds.length; k++) {
            int  menuId = Integer.parseInt(menuIds[k]);
            int z = roleDao.insertRoleAndMenus(roleId, menuId);

        }
        //对于修改角色而言，角色是可以没有权限菜单的，因此只要i>0就表示角色修改成功
        return i>0;

    }

}
